import React, { useRef, useEffect, useState } from 'react';
import { Graph } from 'react-d3-graph';

const ERDiagram = ({ tables, relationships }) => {
  const graphContainerRef = useRef(null);
  const graphInstanceRef = useRef(null);
  const isMountedRef = useRef(true);
  const [graphKey, setGraphKey] = useState(0);

  // 构建节点数据
  const buildNodes = () => {
    return Object.keys(tables).map(tableName => ({
      id: tableName,
      name: tableName,
      symbolType: 'square',
      size: 300,
      fontSize: 14,
      color: '#1890ff',
      renderLabel: true,
    }));
  };
  
  // 构建边数据
  const buildLinks = () => {
    if (!relationships || relationships.length === 0) return [];
    
    return relationships.map(rel => ({
      source: rel.source_table,
      target: rel.target_table,
      label: `${rel.source_column} → ${rel.target_column}`,
      strokeWidth: 2,
      strokeDasharray: rel.cardinality === 'M:1' ? '0' : '5,5',
      color: '#a0a0a0',
      fontSize: 12,
      renderLabel: true,
    }));
  };
  
  // 图形配置
  const graphConfig = {
    automaticRearrangeAfterDropNode: false,
    collapsible: false,
    directed: true,
    focusAnimationDuration: 0.75,
    focusZoom: 1,
    height: 600,
    highlightDegree: 1,
    highlightOpacity: 0.2,
    linkHighlightBehavior: true,
    maxZoom: 8,
    minZoom: 0.1,
    nodeHighlightBehavior: true,
    panAndZoom: true,
    staticGraph: false,
    width: '100%',
    
    node: {
      color: '#1890ff',
      fontColor: 'black',
      fontSize: 14,
      fontWeight: 'normal',
      highlightColor: 'SAME',
      highlightFontSize: 14,
      highlightFontWeight: 'bold',
      highlightStrokeColor: '#ff9e00',
      highlightStrokeWidth: 2,
      mouseCursor: 'pointer',
      opacity: 1,
      renderLabel: true,
      size: 400,
      strokeColor: 'none',
      strokeWidth: 1.5,
      svg: '',
      symbolType: 'circle',
    },
    
    link: {
      color: '#d3d3d3',
      fontColor: '#666',
      fontSize: 12,
      fontWeight: 'normal',
      highlightColor: '#ff9e00',
      highlightFontSize: 12,
      highlightFontWeight: 'bold',
      mouseCursor: 'pointer',
      opacity: 1,
      renderLabel: true,
      semanticStrokeWidth: true,
      strokeWidth: 2,
      type: 'CURVE_SMOOTH',
    },
    
    d3: {
      gravity: -100,
      linkLength: 150,
      linkStrength: 1,
      disableLinkForce: false,
    },
  };
  
  // 自定义节点渲染
  const customNodeRender = (nodeId, x, y, color, config, state, transform, node) => {
    const tableData = tables[nodeId];
    if (!tableData) return null;
    
    const width = 200;
    const height = 120;
    const cornerRadius = 8;
    
    return (
      <g transform={`translate(${x}, ${y})`}>
        {/* 表名标题 */}
        <rect 
          width={width} 
          height={30} 
          rx={cornerRadius} 
          ry={cornerRadius}
          fill={state.hover ? '#e6f7ff' : '#f0f7ff'}
          stroke="#1890ff"
          strokeWidth="1.5"
        />
        <text
          x={width / 2}
          y={18}
          textAnchor="middle"
          fontSize={14}
          fontWeight="bold"
          fill="#1890ff"
        >
          {nodeId}
        </text>
        
        {/* 表主体 */}
        <rect 
          y={30}
          width={width} 
          height={height - 30} 
          rx={cornerRadius} 
          ry={cornerRadius}
          fill="white"
          stroke="#d9d9d9"
          strokeWidth="1"
        />
        
        {/* 表信息 */}
        <text
          x={10}
          y={50}
          fontSize={12}
          fill="#666"
        >
          行数: {tableData.metadata.row_count}
        </text>
        <text
          x={10}
          y={70}
          fontSize={12}
          fill="#666"
        >
          列数: {tableData.metadata.column_count}
        </text>
        
        {/* 列列表 */}
        <g transform="translate(10, 80)">
          {tableData.columns.slice(0, 4).map((col, index) => (
            <text
              key={col.column_name}
              y={index * 15}
              fontSize={11}
              fill="#333"
              fontWeight={col.is_primary ? 'bold' : 'normal'}
            >
              {col.column_name}
              {col.is_primary && (
                <tspan fill="#52c41a" fontWeight="bold"> (PK)</tspan>
              )}
              {col.is_foreign && (
                <tspan fill="#1890ff" fontWeight="bold"> (FK)</tspan>
              )}
            </text>
          ))}
          {tableData.columns.length > 4 && (
            <text y={60} fontSize={11} fill="#999">
              +{tableData.columns.length - 4} more...
            </text>
          )}
        </g>
      </g>
    );
  };
  
  // 处理节点点击
  const onNodeClick = (nodeId) => {
    if (!isMountedRef.current) return;
    console.log(`点击表: ${nodeId}`);
  };
  
  // 处理连接点击
  const onLinkClick = (source, target) => {
    if (!isMountedRef.current) return;
    console.log(`点击关系: ${source} → ${target}`);
  };
  
  // 修复错误的核心部分
  useEffect(() => {
    isMountedRef.current = true;
    
    // 添加事件委托监听器
    const handleWheel = (event) => {
      if (!isMountedRef.current) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }
    };
    
    // 只监听我们的容器内的事件
    const container = graphContainerRef.current;
    if (container) {
      container.addEventListener('wheel', handleWheel, { passive: false });
    }
    
    return () => {
      isMountedRef.current = false;
      
      // 移除事件监听器
      if (container) {
        container.removeEventListener('wheel', handleWheel);
      }
      
      // 直接清除图表DOM内容
      if (graphContainerRef.current) {
        graphContainerRef.current.innerHTML = '';
      }
      
      // 强制在下一次渲染时重新创建图表
      setGraphKey(prev => prev + 1);
    };
  }, []);
  
  // 渲染无数据状态
  if (!tables || Object.keys(tables).length === 0) {
    return (
      <div className="er-diagram-empty">
        <div className="empty-message">
          没有可用的表数据来生成ER图
        </div>
      </div>
    );
  }
  
  if (!relationships || relationships.length === 0) {
    return (
      <div className="er-diagram-empty">
        <div className="empty-message">
          没有可用的关系数据来生成ER图
        </div>
      </div>
    );
  }
  
  return (
    <div 
      className="er-diagram-container" 
      ref={graphContainerRef}
      style={{ position: 'relative', height: '100%' }}
    >
      <Graph
        key={graphKey} // 强制卸载时创建新实例
        id={`er-graph-${graphKey}`} // 使用唯一ID
        data={{
          nodes: buildNodes(),
          links: buildLinks(),
        }}
        config={graphConfig}
        customNodeRender={customNodeRender}
        onClickNode={onNodeClick}
        onClickLink={onLinkClick}
        ref={graphInstanceRef}
      />
    </div>
  );
};

export default ERDiagram;